package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.FileAdapter;
import flc.ast.bean.MyFileBean;
import flc.ast.databinding.ActivityFileBinding;
import flc.ast.dialog.AddDialog;
import flc.ast.dialog.DeleteDialog;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.dialog.TypeDialog;
import flc.ast.utils.Content;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class FileActivity extends BaseAc<ActivityFileBinding> {

    public static String path;
    private String mCurrentRootPath;
    private FileAdapter fileAdapter;
    private List<MyFileBean> mList = new ArrayList<>();
    private int selPosition;
    private String selPath;
    private boolean isEdit;

    @Override
    protected int onCreate() {
        return R.layout.activity_file;
    }

    @Override
    public void onBackPressed() {
        if (isEdit) {
            isEdit = false;
            fileAdapter.setEdit(isEdit);
            mDataBinding.llEdit.setVisibility(View.GONE);
        } else if (mCurrentRootPath.equals(PathUtils.getFilesPathExternalFirst() + path)) {
            super.onBackPressed();
        } else {
            mCurrentRootPath = FileUtils.getDirName(mCurrentRootPath);
            mCurrentRootPath = mCurrentRootPath.substring(0, mCurrentRootPath.length() - 1);
            getData(mCurrentRootPath);
        }
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivFileBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.ivEdit.setOnClickListener(this);
        mDataBinding.tvRename.setOnClickListener(this);
        mDataBinding.tvDetail.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);
        mDataBinding.tvShare.setOnClickListener(this);

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext));
        fileAdapter = new FileAdapter();
        mDataBinding.rvFileList.setAdapter(fileAdapter);
        fileAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivEdit://编辑
                isEdit = true;
                selPath = "";
                fileAdapter.setEdit(isEdit);
                mDataBinding.llEdit.setVisibility(View.VISIBLE);
                break;
            case R.id.ivAdd://添加
                if (mCurrentRootPath.equals(PathUtils.getFilesPathExternalFirst() + path)) {
                    showAddDialog();
                } else {
                    getPermission();
                }
                break;
            case R.id.tvRename://重命名
                if (TextUtils.isEmpty(selPath)) {
                    ToastUtils.showShort(getString(R.string.please_sel_file));
                    return;
                }
                showRenameDialog();
                break;
            case R.id.tvDetail://详情
                if (TextUtils.isEmpty(selPath)) {
                    ToastUtils.showShort(getString(R.string.please_sel_file));
                    return;
                }
                showInfoDialog();
                break;
            case R.id.tvDelete://删除
                if (TextUtils.isEmpty(selPath)) {
                    ToastUtils.showShort(getString(R.string.please_sel_file));
                    return;
                }
                showDeleteDialog();
                break;
            case R.id.tvShare://分享
                if (TextUtils.isEmpty(selPath)) {
                    ToastUtils.showShort(getString(R.string.please_sel_file));
                    return;
                }
                IntentUtil.shareFile(mContext, mList.get(selPosition).getPath());
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            fileAdapter.getItem(selPosition).setSelected(false);
            selPosition = position;
            fileAdapter.getItem(position).setSelected(true);
            fileAdapter.notifyDataSetChanged();
            selPath = mList.get(position).getPath();
        } else {
            String path = fileAdapter.getItem(position).getPath();
            if (FileUtils.isDir(path)) {
                mCurrentRootPath = path;
                getData(mCurrentRootPath);
            } else {
                PlayActivity.videoUri = fileAdapter.getItem(position).getPath();
                startActivity(PlayActivity.class);
            }

        }
    }

    @Override
    protected void initData() {
        mCurrentRootPath = PathUtils.getFilesPathExternalFirst() + path;
        getData(mCurrentRootPath);
    }

    private void getData(String rootPath) {
        selPath = "";
        mDataBinding.tvFileTitle.setText(FileUtils.getFileNameNoExtension(rootPath));
        List<File> files = FileUtils.listFilesInDir(rootPath);
        if (files.size() == 0) {
            mDataBinding.tvFileNoData.setVisibility(View.VISIBLE);
            mDataBinding.rvFileList.setVisibility(View.GONE);
        } else {
            mDataBinding.tvFileNoData.setVisibility(View.GONE);
            mDataBinding.rvFileList.setVisibility(View.VISIBLE);
            mList.clear();
            for (File file : files) {
                mList.add(new MyFileBean(file.getPath()));
            }
            mDataBinding.rvFileList.scrollToPosition(0);
            fileAdapter.setList(mList);
        }
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_storage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        goToSel();
                    }
                }).request();
    }

    private void goToSel() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.VIDEO)
                .minCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        for (SelectMediaEntity entity : data) {
                            String filePath = FileUtil.generateFilePath(Content.myFile + "/" + FileUtils.getFileNameNoExtension(mCurrentRootPath), "." + FileUtils.getFileExtension(entity.getPath()));
                            FileUtils.copy(entity.getPath(), filePath);
                        }
                        getData(mCurrentRootPath);
                        ToastUtils.showShort(getString(R.string.add_suc));
                    }
                });
    }

    private void showTypeDialog() {
        TypeDialog dialog = new TypeDialog(mContext);
        dialog.setListener(new TypeDialog.Ilistener() {

            @Override
            public void clickFolder() {
                showAddDialog();
            }

            @Override
            public void clickVideo() {
                getPermission();
            }
        });
        dialog.show();
    }

    private void showAddDialog() {
        AddDialog dialog = new AddDialog(mContext);
        dialog.setListener(new AddDialog.Ilistener() {
            @Override
            public void clickAddFolder(String name) {
                String path = PathUtils.getFilesPathExternalFirst() + Content.myFile + "/" + name;
                if (FileUtils.isFileExists(path)) {
                    ToastUtils.showShort(getString(R.string.folder_is_exist));
                } else {
                    FileUtils.createOrExistsDir(path);
                    ToastUtils.showShort(getString(R.string.add_folder_suc));
                }
                getData(mCurrentRootPath);
                ToastUtils.showShort(getString(R.string.add_suc));
            }
        });
        dialog.show();
    }

    private void showInfoDialog() {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.path = mList.get(selPosition).getPath();
        dialog.show();
    }

    private void showDeleteDialog() {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                //从此文件夹删除
                FileUtils.delete(mList.get(selPosition).getPath());
                ToastUtils.showShort(getString(R.string.delete_suc));
                getData(mCurrentRootPath);
            }
        });
        dialog.show();
    }

    private void showRenameDialog() {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                if (FileUtils.isDir(mList.get(selPosition).getPath())) {
                    FileUtils.rename(mList.get(selPosition).getPath(), name);
                } else {
                    FileUtils.rename(mList.get(selPosition).getPath(), name + "." + FileUtils.getFileExtension(mList.get(selPosition).getPath()));
                }
                getData(mCurrentRootPath);
            }
        });
        dialog.show();
    }

}